<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频解析服务 - 解析测试</title>
    <link href="/static/bootstrap5/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-4">
        <div class="container">
            <a class="navbar-brand" href="/">视频解析服务</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item"><a class="nav-link" href="/">服务状态</a></li>
                    <li class="nav-item"><a class="nav-link active" href="/parse-test">解析测试</a></li>
                    <li class="nav-item d-none" id="userManageNav"><a class="nav-link" href="/user-manage">用户管理</a></li>
                    <li class="nav-item d-none" id="ipBlacklistNav"><a class="nav-link" href="/ip-blacklist">IP黑名单</a></li>
                    <li class="nav-item d-none" id="configManageNav"><a class="nav-link" href="/config-manage">配置管理</a></li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item" id="loginBtnNav"><a class="nav-link" href="/login">登录</a></li>
                    <li class="nav-item d-none" id="userInfoNav"><span class="nav-link" id="userInfo"></span></li>
                    <li class="nav-item d-none" id="logoutBtnNav">
                        <button class="btn btn-outline-light btn-sm" id="logoutBtn">退出登录</button>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 解析测试表单 -->
    <div class="container">
        <div class="row">
            <div class="col-lg-6 mb-4">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">视频解析参数</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success d-none" id="successAlert" role="alert"></div>
                        <div class="alert alert-danger d-none" id="errorAlert" role="alert"></div>

                        <form id="parseForm">
                            <div class="mb-3">
                                <label for="videoUrl" class="form-label">视频链接 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="videoUrl" 
                                       placeholder="输入抖音/快手链接，如https://v.douyin.com/xxx/" 
                                       value="https://v.douyin.com/abc123/" required>
                            </div>
                            <div class="mb-3">
                                <label for="clientId" class="form-label">客户端ID（可选）</label>
                                <input type="text" class="form-control" id="clientId" placeholder="留空则不验证客户端">
                            </div>
                            <div class="mb-3">
                                <label for="clientSecretKey" class="form-label">客户端密钥（可选）</label>
                                <input type="text" class="form-control" id="clientSecretKey" placeholder="与客户端ID配套使用">
                            </div>
                            <div class="mb-3">
                                <label for="frontToken" class="form-label">前端Token <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="frontToken" 
                                       placeholder="前端生成的Token（MD5(标准化URL)）" required>
                                <div class="form-text">
                                    测试用Token：输入链接后点击「生成测试Token」按钮自动填充
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="timestamp" class="form-label">时间戳 <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="timestamp" required>
                                    <button type="button" class="btn btn-outline-secondary" id="genTimestampBtn">生成当前时间戳</button>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="sign" class="form-label">签名 <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="sign" required>
                                    <button type="button" class="btn btn-outline-secondary" id="genSignBtn">生成测试签名</button>
                                </div>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-secondary" id="genTestParamsBtn">填充测试参数</button>
                                <button type="submit" class="btn btn-primary">开始解析</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- 解析结果展示 -->
            <div class="col-lg-6">
                <div class="card shadow d-none" id="resultCard">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0">解析结果</h5>
                    </div>
                    <div class="card-body">
                        <!-- 视频基本信息 -->
                        <div class="mb-4">
                            <h6>视频标题</h6>
                            <p class="card-text" id="videoTitle">-</p>
                            
                            <h6 class="mt-3">视频封面</h6>
                            <img id="videoCover" src="" alt="视频封面" class="img-fluid rounded" style="max-height: 200px;">
                        </div>

                        <!-- 清晰度选择与下载 -->
                        <div class="mt-4">
                            <h6>选择清晰度下载</h6>
                            <div id="qualityList" class="list-group">
                                <!-- JS动态生成清晰度选项 -->
                            </div>
                        </div>

                        <!-- 图片下载（如有） -->
                        <div class="mt-4 d-none" id="imagesSection">
                            <h6>视频配图下载</h6>
                            <div id="imagesList" class="row g-2 mt-2">
                                <!-- JS动态生成图片下载按钮 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/bootstrap5/js/bootstrap.bundle.min.js"></script>
    <script>
        // 1. 权限控制
        async function checkAuth() {
            const token = localStorage.getItem('access_token');
            const loginBtnNav = document.getElementById('loginBtnNav');
            const userInfoNav = document.getElementById('userInfoNav');
            const logoutBtnNav = document.getElementById('logoutBtnNav');
            const userManageNav = document.getElementById('userManageNav');
            const ipBlacklistNav = document.getElementById('ipBlacklistNav');
            const configManageNav = document.getElementById('configManageNav');

            if (token) {
                loginBtnNav.classList.add('d-none');
                userInfoNav.classList.remove('d-none');
                logoutBtnNav.classList.remove('d-none');

                try {
                    const response = await fetch('/users/me', {
                        headers: { 'Authorization': `Bearer ${token}` }
                    });
                    
                    if (!response.ok) {
                        throw new Error('Token无效');
                    }
                    
                    const user = await response.json();
                    document.getElementById('userInfo').textContent = `当前用户：${user.username}`;

                    if (user.is_admin) {
                        userManageNav.classList.remove('d-none');
                        ipBlacklistNav.classList.remove('d-none');
                        configManageNav.classList.remove('d-none');
                    }
                } catch (err) {
                    localStorage.removeItem('access_token');
                    window.location.href = '/login';
                }
            } else {
                window.location.href = '/login';
            }

            // 生成默认时间戳
            document.getElementById('timestamp').value = Math.floor(Date.now() / 1000);
        }

        // 2. 生成测试参数（自动填充Token和签名）
        document.getElementById('genTestParamsBtn').addEventListener('click', () => {
            const videoUrl = 'https://v.douyin.com/abc123/'; // 测试链接
            const clientId = '';
            const clientSecretKey = '';
            
            // 标准化URL（模拟前端逻辑）
            const normalizedUrl = new URL(videoUrl).href.replace(/\/$/, '');
            // 生成前端Token（MD5标准化URL）
            const frontToken = CryptoJS.MD5(normalizedUrl).toString();
            // 生成时间戳
            const timestamp = Math.floor(Date.now() / 1000);
            // 生成签名
            const signSource = `${normalizedUrl}${timestamp}${clientSecretKey}` || `${frontToken}${timestamp}`;
            const sign = CryptoJS.MD5(signSource).toString();

            // 填充表单
            document.getElementById('videoUrl').value = videoUrl;
            document.getElementById('clientId').value = clientId;
            document.getElementById('clientSecretKey').value = clientSecretKey;
            document.getElementById('frontToken').value = frontToken;
            document.getElementById('timestamp').value = timestamp;
            document.getElementById('sign').value = sign;

            // 提示
            alert('测试参数已填充，可直接点击「开始解析」');
        });

        // 3. 生成当前时间戳
        document.getElementById('genTimestampBtn').addEventListener('click', () => {
            document.getElementById('timestamp').value = Math.floor(Date.now() / 1000);
        });

        // 4. 生成测试签名
        document.getElementById('genSignBtn').addEventListener('click', () => {
            const videoUrl = document.getElementById('videoUrl').value;
            const clientSecretKey = document.getElementById('clientSecretKey').value;
            const frontToken = document.getElementById('frontToken').value;
            const timestamp = document.getElementById('timestamp').value;

            if (!videoUrl || !frontToken || !timestamp) {
                alert('请先填写视频链接、前端Token和时间戳');
                return;
            }

            try {
                // 标准化URL
                const normalizedUrl = new URL(videoUrl).href.replace(/\/$/, '');
                // 生成签名
                const signSource = clientSecretKey ? `${normalizedUrl}${timestamp}${clientSecretKey}` : `${frontToken}${timestamp}`;
                const sign = CryptoJS.MD5(signSource).toString();

                document.getElementById('sign').value = sign;
            } catch (err) {
                alert('URL格式不正确，请检查链接');
            }
        });

        // 5. 解析表单提交
        document.getElementById('parseForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const videoUrl = document.getElementById('videoUrl').value;
            const clientId = document.getElementById('clientId').value;
            const clientSecretKey = document.getElementById('clientSecretKey').value;
            const frontToken = document.getElementById('frontToken').value;
            const timestamp = document.getElementById('timestamp').value;
            const sign = document.getElementById('sign').value;
            const token = localStorage.getItem('access_token');

            // 显示加载状态
            const successAlert = document.getElementById('successAlert');
            const errorAlert = document.getElementById('errorAlert');
            const resultCard = document.getElementById('resultCard');
            successAlert.classList.add('d-none');
            errorAlert.classList.add('d-none');
            resultCard.classList.add('d-none');

            try {
                // 构建请求URL
                const params = new URLSearchParams();
                params.append('url', videoUrl);
                params.append('token', frontToken);
                params.append('timestamp', timestamp);
                params.append('sign', sign);
                if (clientId) params.append('clientId', clientId);
                if (clientSecretKey) params.append('clientSecretKey', clientSecretKey);

                // 调用解析API
                const headers = {};
                if (token) headers['Authorization'] = `Bearer ${token}`;

                const response = await fetch(`/api/parse?${params.toString()}`, { headers });
                const data = await response.json();

                if (response.ok && data.code === 200) {
                    // 解析成功：展示结果
                    successAlert.textContent = '解析成功！';
                    successAlert.classList.remove('d-none');
                    resultCard.classList.remove('d-none');

                    // 填充基本信息
                    document.getElementById('videoTitle').textContent = data.data.title || '未知标题';
                    document.getElementById('videoCover').src = data.data.cover || 'https://picsum.photos/400/300?random=10';

                    // 填充清晰度列表
                    const qualityList = document.getElementById('qualityList');
                    qualityList.innerHTML = '';
                    data.data.quality.forEach(quality => {
                        const item = document.createElement('a');
                        item.href = `/api/download_video?url=${encodeURIComponent(quality.url)}`;
                        item.className = 'list-group-item list-group-item-action';
                        item.target = '_blank';
                        item.textContent = `${quality.level}（${quality.filesize}）- 点击下载`;
                        qualityList.appendChild(item);
                    });

                    // 填充图片列表（如有）
                    const imagesSection = document.getElementById('imagesSection');
                    const imagesList = document.getElementById('imagesList');
                    imagesList.innerHTML = '';
                    if (data.data.images && data.data.images.length > 0) {
                        imagesSection.classList.remove('d-none');
                        data.data.images.forEach((imgUrl, index) => {
                            const col = document.createElement('div');
                            col.className = 'col-6';
                            col.innerHTML = `
                                <a href="/api/download_pic?url=${encodeURIComponent(imgUrl)}" target="_blank" class="d-block">
                                    <img src="${imgUrl}" alt="配图${index+1}" class="img-fluid rounded" style="max-height: 100px;">
                                    <div class="text-center mt-1">下载配图${index+1}</div>
                                </a>
                            `;
                            imagesList.appendChild(col);
                        });
                    } else {
                        imagesSection.classList.add('d-none');
                    }
                } else {
                    errorAlert.textContent = data.msg || '解析失败';
                    errorAlert.classList.remove('d-none');
                }
            } catch (err) {
                errorAlert.textContent = `网络错误：${err.message}`;
                errorAlert.classList.remove('d-none');
            }
        });

        // 6. 退出登录
        document.getElementById('logoutBtn').addEventListener('click', () => {
            localStorage.removeItem('access_token');
            window.location.href = '/login';
        });

        // 加载MD5库（用于生成测试Token和签名）
        const md5Script = document.createElement('script');
        md5Script.src = 'https://cdn.jsdelivr.net/npm/crypto-js@4.2.0/crypto-js.min.js';
        md5Script.onload = checkAuth; // 加载完成后检查权限
        document.head.appendChild(md5Script);
    </script>
</body>
</html>
    